package com.carrentalplatform.controller;

import com.carrentalplatform.model.Vehicle;
import com.carrentalplatform.service.VehicleService;
import com.carrentalplatform.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/api/admin/upload")
public class UploadController {

    private final VehicleService vehicleService;

    @Value("${file.upload.path:./uploads}")
    private String uploadPath;
    
    @Value("${file.upload.url-prefix:/uploads}")
    private String urlPrefix;

    public UploadController(VehicleService vehicleService) {
        this.vehicleService = vehicleService;
    }

    /**
     * 上传车辆图片
     */
    @PostMapping("/vehicleImage")
    public Result<Map<String, String>> uploadVehicleImage(@RequestParam("file") MultipartFile file,
                                                          @RequestParam(value = "vehicleId", required = false) Long vehicleId) {
        if (file.isEmpty()) {
            return Result.fail("上传文件不能为空");
        }
        
        try {
            // 生成存储路径（示例：yyyyMMdd/xxxxxxxx.jpg）
            String originalFilename = file.getOriginalFilename();
            String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String storagePath = uploadPath + "/vehicle/" + datePath;
            File directory = new File(storagePath);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 生成新文件名
            String newFilename = UUID.randomUUID() + getFileExtension(originalFilename);

            // 保存文件
            Path targetPath = Paths.get(storagePath, newFilename);
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

            // 生成访问路径（示例：/uploads/vehicle/20240518/abc.jpg）
            // 确保URL以/开头，方便前端处理
            String normalizedUrlPrefix = urlPrefix.startsWith("/") ? urlPrefix : "/" + urlPrefix;
            String fileUrl = normalizedUrlPrefix + "/vehicle/" + datePath + "/" + newFilename;
            
            Map<String, String> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("filename", newFilename);
            
            // 记录已保存的文件路径
            System.out.println("已保存文件: " + targetPath + ", 访问URL: " + fileUrl);

            // 如果存在车辆ID，更新车辆记录
            if (vehicleId != null) {
                Vehicle vehicle = new Vehicle();
                vehicle.setId(vehicleId);
                vehicle.setImageUrl(fileUrl);
                vehicleService.updateById(vehicle);
                System.out.println("已更新车辆 " + vehicleId + " 的图片为: " + fileUrl);
            }
            
            return Result.success(result);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("文件上传失败: " + e.getMessage());
        }
    }

    // 新增文件扩展名处理方法
    private String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf(".") == -1) {
            return "";
        }
        return filename.substring(filename.lastIndexOf("."));
    }
}